const { exec,escape } = require('../db/mysql');
const { genPassword } = require('../util/cryp');
const login = (username, password) => {
    // 先使用假数据
    username = escape(username);

    password = genPassword(password);
    password = escape(password);
  const sql = `
        select username, realname from users where username=${username} and password=${password}
    `;
  return exec(sql).then(rows => {
      return rows[0] || {}
    })

};

const register = (username, password, realname='') => {
  if (!username || !password) {
    return Promise.reject("请检查用户名或密码输入是否正确？");
  }
  username = escape(username);
  password = escape(genPassword(password));
  realname = escape(realname);

  const sql = `insert into users (username, password, realname) values (${username}, ${password}, '${realname}')`;
  console.log('', sql);
  return exec(sql).then(rows => {
    return Promise.resolve(rows[0] || {});
  }).catch(err => {
    return Promise.reject("向数据库插入用户注册数据失败", err);
  })
};
module.exports = {
    login,
    register
};